import XLSX from 'xlsx'

/**
 * 解析excel表头信息
 * @param {*} sheet
 * @returns
 */
export const getHeaderRow = (sheet) => {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}

/**
 * 判断文件是否是excel文件
 * @param {*} file 校验文件
 * @returns Boolean
 */
export const isExcel = file => {
  try {
    return /\.(xlsx|xls|csv)$/.test(file.name)
  } catch (error) {
    return false
  }
}

/**
 * 解析excel导出的时间格式
 * @param {*} numb
 * @returns
 */
export const formatDate = numb => {
  const time = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  return (
    year +
    '-' +
    (month.padStart(2, '0')) +
    '-' +
    (date.padStart(2, '0'))
  )
}

/**
 * 通过时间key格式化list中的时间
 * @param {*} list 要格式的list
 * @param {*} key 时间关键字
 * @returns 格式化之后的list
 */
export const formatDateByKey = (list, key) => {
  return list.map(row => {
    if (typeof row[key] === 'number') {
      row[key] = formatDate(row[key])
    }
    return row
  })
}
